package com.origin.uilibrary.viewpager;


import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import androidx.viewpager.widget.ViewPager;

import com.origin.utils.log.LogUtils;

/**
 * ViewPager DynamicHeight解决方案
 */
public class DynamicHeightViewPager extends ViewPager {

    // 默认为false
    public boolean isWrap;

    /**
     * Constructor
     *
     * @param context the context
     */
    public DynamicHeightViewPager(Context context) {
        super(context);
        final ViewPager pager = this;
        pager.addOnPageChangeListener(new SimpleOnPageChangeListener() {
            private int position;
            private int oldPositon;

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                this.position = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (!isWrap){
                    return;
                }
                if (state == 2) {
                    requestLayout();
                }
            }

        });
    }

    /**
     * Constructor
     *
     * @param context the context
     * @param attrs   the attribute set
     */
    public DynamicHeightViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    //    @Override
//    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//
//        // find the first child view
//        View view = getChildAt(0);
//        if (view != null) {
//            // measure the first child view with the specified measure spec
//            view.measure(widthMeasureSpec, heightMeasureSpec);
//        }
//
//        setMeasuredDimension(getMeasuredWidth(), measureHeight(heightMeasureSpec, view));
//    }

    /**
     * 解决pager中视图高度不一致的情况 动态更改pager高度
     *
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */




    @Override
    protected void onMeasure(final int widthMeasureSpec, int heightMeasureSpec) {
        if (!isWrap){
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            return;
        }
        int height = 0;
        View v = getChildAt(0);
        if (v != null) {
            v.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            height = v.getMeasuredHeight();

        }
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    }
}
